package com.zqh.irmadscore.utils.jwtUtils;


import cn.hutool.json.JSONObject;
import cn.hutool.jwt.*;
import com.zqh.irmadscore.utils.resultUtils.ResultCodeEnum;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;

public class JwtUtil {
    private static long tokenExpiration = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15;
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(Long userId, String username) {

        var map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("userId", userId);
                put("username", username);
                put("uid", Integer.parseInt("123"));
                put("tokenSignKey", tokenSignKey);
                put("expire_time", tokenExpiration);
            }
        };

        String token =  JWTUtil.createToken(map, "1234".getBytes());


        return token;
    }

/**
 * 解析并验证JWT令牌
 * @param token JWT令牌字符串
 * @return 包含有效负载声明的JSON对象
 * @throws Exception 当出现以下情况时抛出异常：
 *                   1. token为空或空字符串（ADMIN_LOGIN_AUTH）
 *                   2. token过期（TOKEN_EXPIRED）
 *                   3. token验证失败（TOKEN_INVALID）
 */
public static JSONObject parseToken(String token) throws Exception {
    // 空值检查
    if (token == null || token.isEmpty()) {
        throw new Exception(ResultCodeEnum.ADMIN_LOGIN_AUTH.getMessage());
    }
    try {
        // 解析JWT基础结构
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject claims = jwt.getPayloads();
        // 处理过期时间校验
        Object expObj = claims.get("exp");

        if (expObj != null) {
            // 转换时间戳并验证过期时间
            long expSeconds = Long.parseLong(expObj.toString());
            long expirationTime = expSeconds * 1000L;
            if (expirationTime < System.currentTimeMillis()) {
                throw new Exception(ResultCodeEnum.TOKEN_EXPIRED.getMessage());
            }
        }
        return claims;
    } catch (Exception e) {
        // 统一异常处理
        throw new Exception(ResultCodeEnum.TOKEN_INVALID.getMessage(), e);
    }
}


    public static void main(String[] args) throws Exception {

        var token = createToken(1111L, "15986989793");

        System.out.println(token);
        System.out.println(parseToken(token));

    }

}
